/*
 * Funny Language - a free style programming language.
 * Copyright (C) 2015 by fanguangping (fanguangping@163.com)
 * mapqueue.c
 */

#include <stdlib.h>
#include "mapqueue.h"
#include "../base/cmemory.h"

KeyValueNode *alloc_map_node() {
	return (KeyValueNode *) sys_malloc(sizeof(KeyValueNode));
}

void add_key_value(Queue *queue, String key, void *value) {
	if (queue == NULL || key == NULL || value == NULL)
		return;

	KeyValueNode *node = alloc_map_node();
	node->key = key;
	node->value = value;
	enqueue(queue, node);
}

void *find_value(Queue *queue, String key) {
	if (queue == NULL || key == NULL)
		return NULL;

	KeyValueNode *keyValueNode = NULL;
	QueueNode *node = queue->head;

	while (node != NULL) {
		keyValueNode = (KeyValueNode *) (node->element);
		if (equals_string(key, keyValueNode->key)) {
			return keyValueNode->value;
		}
		node = node->next;
	}
	return NULL;
}

Queue *find_values(Queue *queue, String key) {
	if (queue == NULL || key == NULL)
		return NULL;

	KeyValueNode *keyValueNode = NULL;
	Queue *result = init_queue();
	QueueNode *node = queue->head;

	while (node != NULL) {
		keyValueNode = (KeyValueNode *) (node->element);
		if (equals_string(key, keyValueNode->key)) {
			enqueue(result, keyValueNode->value);
		}
		node = node->next;
	}
	return result;
}
